package com.zpz.framework.zpzoauth.common.verificationcode;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthCommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Component
public class ZpzOauthVerificationCode {
    @Resource
    private ZpzOauthRedisVerificationCodeCache zpzOauthRedisVerificationCodeCache;
    /**
    * 获取验证码TOKEN
    * */
    public String getToken(Integer size, Long expire, String type,String subject){
        if(size == null) {
            size = ZpzOauthCommonConstant.NUMBER_VRIFICATION_CODE_LENGTH;
        }
        if(expire == null){
            expire = ZpzOauthCommonConstant.EXPIRE_VRIFICATION_CODE;
        }
        String code = "";
        if(ZpzOauthCommonConstant.NUMBER_VRIFICATION_CODE.equals(type)){
            code = ZpzOauthVerificationCodeUtils.generateNumberVerifyCode(size);
        }else{
            code = ZpzOauthVerificationCodeUtils.generateVerifyCode(size);
        }
        String token = UUID.randomUUID().toString().replaceAll("-","");
        String realToken = token;
        if(StringUtils.isNotEmpty(subject)){
            realToken = subject + "@" + token;
        }
        zpzOauthRedisVerificationCodeCache.set(ZpzOauthCommonConstant.VERIFICATION_CODE_CACHE_NAME,realToken, code,expire);
        return token;
    }
    /**
    * 验证验证码
    * */
    public boolean validate(String token, String code, String subject,boolean ignoreCase) {
        if(StringUtils.isEmpty(code)){
            return false;
        }
        if(StringUtils.isNotEmpty(subject)){
            token = subject + "@" + token;
        }
        String value = zpzOauthRedisVerificationCodeCache.get(ZpzOauthCommonConstant.VERIFICATION_CODE_CACHE_NAME,token);
        if(StringUtils.isEmpty(value)){
            return false;
        }

        return ignoreCase ? code.equalsIgnoreCase(value) : code.equals(value);
    }
    /**
     * 获取验证码图片
     * */
    public void renderImage(String token, OutputStream outputStream) throws IOException {
        // 生成随机字串
        String value = this.getCode(token);
        // 生成图片
        int w = 100, h = 30;
        ZpzOauthVerificationCodeUtils.outputImage(w, h, outputStream, value);
    }
    public String getCode(String token){
        return zpzOauthRedisVerificationCodeCache.get(ZpzOauthCommonConstant.VERIFICATION_CODE_CACHE_NAME,token);
    }
}
